<template>
	<view class="address-edit-content" :data-theme="themeStyle">
    <header-back :headerTitle="$lang('title')"></header-back>
    <view class="edit-wrap">
			<view class="tip">{{ $lang('addressInformation') }}</view>
			<view class="edit-item">
				<text class="tit">
					{{ $lang('consignee') }}
					<text>*</text>
				</text>
				<input
					class="uni-input"
					type="text"
					placeholder-class="placeholder-class"
					:placeholder="$lang('consigneePlaceholder')"
					maxlength="30"
					name="name"
					v-model="formData.name"
				/>
			</view>
			<view class="edit-item">
				<text class="tit">
					{{ $lang('mobile') }}
					<text>*</text>
				</text>
				<view class="input-wrap">
<!--					<view class="wrap" @click="$refs.countryPopup.open()">-->
<!--						<view class="h6">+{{selectIndex}}</view>-->
<!--						<image src="/static/icon/icon_down_01.png" class="down-icon" mode=""></image>-->
<!--					</view>-->
					<input
						class="uni-input"
						type="number"
						placeholder-class="placeholder-class"
						:placeholder="$lang('mobilePlaceholder')"
						maxlength="11"
						value=""
						v-model="formData.mobile"
					/>
				</view>
			</view>
			<view class="edit-item">
				<text class="tit">{{ $lang('telephone') }}</text>
				<input
					class="uni-input"
					type="text"
					placeholder-class="placeholder-class"
					:placeholder="$lang('telephonePlaceholder')"
					maxlength="20"
					value=""
					v-model="formData.telephone"
				/>
			</view>
			<!--  外卖地址区分 -->
			<view class="edit-item">
				<text class="tit">
					{{ $lang('receivingCity') }}
					<text>*</text>
				</text>
				<!-- <view class="text_inp" :class="{ empty: !formData.full_address, 'color-tip': !formData.full_address }" @click="selectAddress">
					{{ formData.full_address ? formData.full_address : '请选择省市区县' }}
				</view>
				<text @click="selectAddress" class="padding-left iconfont iconlocation"></text> -->
				<input class="uni-input" type="text" placeholder-class="placeholder-class" 
				placeholder="" maxlength="50" v-model="formData.full_address" />
			</view>
			<!-- <view class="edit-item">
				<text class="tit">
					{{ $lang('receivingCity') }}
					<text>*</text>
				</text>
				<pick-regions :default-regions="defaultRegions" @getRegions="handleGetRegions">
					<text class="select-address " :class="{ empty: !formData.full_address, 'color-tip': !formData.full_address }">
						{{ formData.full_address ? formData.full_address : '请选择省市区县' }}
					</text>
				</pick-regions>
			</view> -->
			<view class="edit-item">
				<text class="tit">
					{{ $lang('address') }}
					<text>*</text>
				</text>
				<input class="uni-input" type="text" placeholder-class="placeholder-class" :placeholder="$lang('addressPlaceholder')" maxlength="50" v-model="formData.address" />
				<!-- <text @click="selectAddress" class="padding-left iconfont iconlocation"></text> -->
			</view>
		</view>
		
		<!-- 区号弹框 -->
		<uni-popup ref="countryPopup" type="right" :mask-click="true">
			<view class="country-popup">
				<view class="shops-header-box">
					<view class="shops-header">
						<view class="shops-left" @click.stop="$refs.countryPopup.close()">
							<image  src="/static/icon/arrow_left_01.png" class="arrow-l" mode=""></image>
							<view class="shops-header-title">{{ $lang('chooseAnAreaCode') }}</view>
						</view>
						<view class="shops-right" ></view>				
					</view>
					<view class="search-wrap uni-flex uni-row">
						<view class="flex-item input-wrap">
							<input class="uni-input" maxlength="50" v-model="keyword" confirm-type="search" @confirm="searchFn()" :placeholder="$lang('pleaseEnterCountryName')" />
							<text class="iconfont iconsousuo1" @click.stop="searchFn()"></text>
						</view>
					</view>
				</view>
				<view class="country-ul">
					<view class="country-li" v-for="(obj,l) in countryArr" :key="l" @click.stop="selectFn(obj,l)">
						<view class="li-name">
							<text >{{obj.name}} <text class="h6">+{{obj.tel}}</text></text>
							<image v-show="selectIndex == obj.tel" src="/static/icon/icon_select_01.png" class="sel-icon" mode=""></image>
						</view>
					</view>
				</view>
			</view>
		</uni-popup>
		
		
		<view class="btn">
			<button type="primary" class="add" @click="saveAddress">{{ $lang('save') }}</button>
		</view>
		<loading-cover ref="loadingCover"></loading-cover>
	</view>
</template>

<script>
import pickRegions from '@/components/pick-regions/pick-regions.vue';
import validate from 'common/js/validate.js';
import globalConfig from '@/common/js/golbalConfig.js';
import Config from '@/common/js/config.js';
export default {
	components: {
		pickRegions
	},
	data() {
		return {
			formData: {
				id: 0,
				name: '',
				mobile: '',
				telephone: '',
				province_id: '',
				city_id: '',
				district_id: '',
				community_id: '',
				address: '',
				full_address: '',
				latitude: 0,
				longitude: 0,
				is_default: 1
			},
			address: '',
			addressValue: '',
			back: '/otherpages/member/address/address', // 返回页
			redirect: 'redirectTo', // 跳转方式
			flag: false, //防重复标识
			defaultRegions: [],
			localType:2,
			countryArr: [],
			selectIndex: '86',
			keyword: '',
			copyCountry: [],
		};
	},
	onLoad(option) {
		if (option.back) this.back = option.back;
		if (option.redirect) this.redirect = option.redirect;
		if (option.type) this.localType = option.type;
		if (option.id && !option.name) {
			this.formData.id = option.id;
			this.getAddressDetail();
		} else if (option.name) {
			if (uni.getStorageSync('addressInfo')) this.formData = uni.getStorageSync('addressInfo');
			this.formData.address = option.name;
			this.getAddress(option.latng);
			//给formData复制
			var tempArr = this.getQueryVariable('latng').split(',');
			this.formData.latitude = tempArr[0];
			this.formData.longitude = tempArr[1];
		}
		this.getCountry();
	},
	onBackPress() {
		uni.setStorageSync('addressInfo', '');
	},
	onShow() {
		// 刷新多语言
		this.$langConfig.refresh();
		if (this.formData.id) {
			uni.setNavigationBarTitle({
				title: this.$lang('editShippingAddress')
			});
		} else {
			uni.setNavigationBarTitle({
				title: this.$lang('newShippingAddress')
			});
		}
	},
	onReady() {
		this.$refs.loadingCover.hide();
	},
	onHide() {
		this.flag = false;
	},
	mixins: [globalConfig],
	methods: {
		searchFn(){
			let keyword = this.keyword.trim();
			if(!keyword){
				this.countryArr = this.copyCountry;
			}
			this.countryArr = this.copyCountry.filter(v=>{
				if(v.name.includes(keyword)){
					return v;
				} 
			})
		},
		selectFn(obj,index){
			this.selectIndex = obj.tel;
			this.$refs.countryPopup.close()
		},
		// 获取区号
		getCountry(){
			this.$api.sendRequest({
				url: '/api/register/countrylist',
				method: 'get',
				success:res=>{
					if(res.code == 0){
						this.copyCountry = this.countryArr = res.data;
					}
				}
			})
		},
		getAddressDetail() {
			this.$api.sendRequest({
				url: '/api/memberaddress/info',
				data: {
					id: this.formData.id
				},
				success: res => {
					let data = res.data;
					if (data != null) {
						this.formData.name = data.name;
						this.formData.mobile = data.mobile;
						this.formData.telephone = data.telephone;
						this.formData.address = data.address;
						this.formData.full_address = data.full_address;
						this.formData.latitude = data.latitude;
						this.formData.longitude = data.longitude;
						this.formData.is_default = data.is_default;
						this.addressValue = '';
						this.addressValue += res.data.province_id != undefined ? res.data.province_id : '';
						this.addressValue += res.data.city_id != undefined ? '-' + res.data.city_id : '';
						this.addressValue += res.data.district_id != undefined ? '-' + res.data.district_id : '';
						this.localType = data.type;
						this.defaultRegions = [data.province_id, data.city_id, data.district_id];
					}
					if (this.$refs.loadingCover) this.$refs.loadingCover.hide();
				},
				fail: res => {
					if (this.$refs.loadingCover) this.$refs.loadingCover.hide();
				}
			});
		},
		//获取详细地址
		getAddress(value) {
			this.$api.sendRequest({
				url: '/api/memberaddress/tranAddressInfo',
				data: {
					latlng: value
				},
				success: res => {
					if (res.code == 0) {
						this.formData.full_address = '';
						this.formData.full_address += res.data.province != undefined ? res.data.province : '';
						this.formData.full_address += res.data.city != undefined ? '-' + res.data.city : '';
						this.formData.full_address += res.data.district != undefined ? '-' + res.data.district : '';
						this.addressValue = '';
						this.addressValue += res.data.province_id != undefined ? res.data.province_id : '';
						this.addressValue += res.data.city_id != undefined ? '-' + res.data.city_id : '';
						this.addressValue += res.data.district_id != undefined ? '-' + res.data.district_id : '';
					} else {
						this.showToast({
							title: this.$lang('theDataIsWrong')
						});
					}
				}
			});
		},
		// 获取选择的地区
		handleGetRegions(regions) {
			this.formData.full_address = '';
			this.formData.full_address += regions[0] != undefined ? regions[0].label : '';
			this.formData.full_address += regions[1] != undefined ? '-' + regions[1].label : '';
			this.formData.full_address += regions[2] != undefined ? '-' + regions[2].label : '';
			this.addressValue = '';
			this.addressValue += regions[0] != undefined ? regions[0].value : '';
			this.addressValue += regions[1] != undefined ? '-' + regions[1].value : '';
			this.addressValue += regions[2] != undefined ? '-' + regions[2].value : '';
		},

		selectAddress() {
			// // #ifdef MP
			// uni.chooseLocation({
			// 	success: res => {
			// 		this.formData.latitude = res.latitude;
			// 		this.formData.longitude = res.longitude;
			// 		this.formData.address = res.name;
			// 		this.getAddress(res.latitude + ',' + res.longitude);
			// 	},
			// 	fail(res) {
			// 		uni.getSetting({
			// 			success: function(res) {
			// 				var statu = res.authSetting;
			// 				if (!statu['scope.userLocation']) {
			// 					uni.showModal({
			// 						title: '是否授权当前位置',
			// 						content: '需要获取您的地理位置，请确认授权，否则地图功能将无法使用',
			// 						success(tip) {
			// 							if (tip.confirm) {
			// 								uni.openSetting({
			// 									success: function(data) {
			// 										if (data.authSetting['scope.userLocation'] === true) {
			// 											this.$util.showToast({
			// 												title: '授权成功'
			// 											});
			// 											//授权成功之后，再调用chooseLocation选择地方
			// 											setTimeout(function() {
			// 												uni.chooseLocation({
			// 													success: data => {
			// 														this.formData.latitude = res.latitude;
			// 														this.formData.longitude = res.longitude;
			// 														this.formData.address = res.name;
			// 														this.getAddress(res.latitude + ',' + res.longitude);
			// 													}
			// 												});
			// 											}, 1000);
			// 										}
			// 									}
			// 								});
			// 							} else {
			// 								this.$util.showToast({
			// 									title: '授权失败'
			// 								});
			// 							}
			// 						}
			// 					});
			// 				}
			// 			}
			// 		});
			// 	}
			// });
			// // #endif
			// #ifdef H5
			var urlencode = this.formData;
			uni.setStorageSync('addressInfo', urlencode);
			let backurl = Config.h5Domain + '/otherpages/member/address_edit/address_edit?type=' + this.localType;
			// let backurl ='http://localhost:8080/h5/otherpages/member/address_edit/address_edit?type=' + this.localType;
			if (this.formData.id) backurl += '&id=' + this.formData.id;
			if (this.back) backurl += '&back=' + this.back;

			window.location.href = 'https://apis.map.qq.com/tools/locpicker?search=1&type=0&backurl=' + encodeURIComponent(backurl) + '&key=' + Config.mpKey + '&referer=myapp';
			// #endif
		},
		getQueryVariable(variable) {
			var query = window.location.search.substring(1);
			var vars = query.split('&');
			for (var i = 0; i < vars.length; i++) {
				var pair = vars[i].split('=');
				if (pair[0] == variable) {
					return pair[1];
				}
			}
			return false;
		},
		vertify() {
			this.formData.name = this.formData.name.trim();
			this.formData.mobile = this.formData.mobile.trim();
			this.formData.address = this.formData.address.trim();
			var rule = [
				{
					name: 'name',
					checkType: 'required',
					errorMsg: this.$lang('pleaseTypeInYourName')
				},
				{
					name: 'mobile',
					checkType: 'required',
					errorMsg: this.$lang('pleaseEnterPhoneNumber')
				},
				// {
				// 	name: 'mobile',
				// 	checkType: 'phoneno',
				// 	errorMsg: '请输入正确的手机号'
				// },
				{
					name: 'full_address',
					checkType: 'required',
					errorMsg: this.$lang('pleaseSelectAProvinceMunicipalityOrCounty')
				},
				{
					name: 'address',
					checkType: 'required',
					errorMsg: this.$lang('theDetailedAddressCannotBeEmpty')
				}
			];
			var checkRes = validate.check(this.formData, rule);
			if (checkRes) {
				return true;
			} else {
				this.$util.showToast({
					title: validate.error
				});
				this.flag = false;
				return false;
			}
		},
		saveAddress() {
			if (this.flag) return;
			this.flag = true;
			if (this.vertify()) {
				// this.formData.mobile = this.selectIndex+'-'+this.formData.mobile
				let addressValueArr = this.addressValue.split('-'),
					data = {},
					url = '';

				data = {
					name: this.formData.name,
					mobile: this.formData.mobile,
					telephone: this.formData.telephone,
					province_id: addressValueArr[0],
					city_id: addressValueArr[1],
					district_id: addressValueArr[2],
					community_id: 0,
					address: this.formData.address,
					full_address: this.formData.full_address,
					latitude: this.formData.latitude,
					longitude: this.formData.longitude,
					is_default: this.formData.is_default,
					type: this.localType
				};

				url = 'add';
				if (this.formData.id) {
					url = 'edit';
					data.id = this.formData.id;
				}
				this.$api.sendRequest({
					url: '/api/memberaddress/' + url,
					data: data,
					success: res => {
						this.flag = false;
						if (res.code == 0) {
							if (this.back != '' && url != 'edit') {
								// this.$util.redirectTo(this.back, {}, this.redirect);
								let jump = true;
								let arr = getCurrentPages().reverse();
								for (let i = 0; i < arr.length; i++) {
									if (this.back.indexOf(arr[i].route) != -1) {
										jump = false;
										uni.navigateBack({
											delta: i
										});
										break;
									}
								}
								if (jump) {
									this.$util.redirectTo(this.back, {}, 'redirectTo');
								}
							} else {
								this.$util.showToast({
									title: res.message
								});
								this.$util.redirectTo(this.back, {}, 'redirectTo');
							}
							uni.removeStorageSync('addressInfo');
						}
					},
					fail: res => {
						this.flag = false;
					}
				});
			}
		}
	}
};
</script>

<style lang="scss">
/deep/ pick-regions,
.pick-regions {
	flex: 1;
}

.edit-wrap {
	background: #fff;
	overflow: hidden;

	.tip {
		padding: 20rpx 30rpx 10rpx;
		background-color: #f8f8f8;
		color: $color-tip;
	}
}

.edit-item {
	display: flex;
	align-items: center;
	margin: 0 30rpx;
	min-height: 100rpx;
	background-color: #fff;

	.text_inp {
		margin-left: $margin-updown;
		flex: 1;
	}

	.tit {
		width: 148rpx;

		text {
			margin-left: 10rpx;
			color: #31bb6d;
		}

		&.margin_tit {
			align-self: flex-start;
			margin-top: 24rpx;
		}
	}

	.iconlocation {
		color: #606266;
		align-self: flex-start;
		margin-top: 20rpx;
	}

	.select-address {
		display: block;
		margin-left: 10rpx;

		&.empty {
			color: #808080;
		}
	}
	.input-wrap {
		display: flex;
		align-items: center;
		.wrap {
			display: flex;
			align-items: center;
			.h6 {
				font-size: 28rpx;
				color: #303133;
			}
			.down-icon {
				width: 24rpx;
				height: 24rpx;
				display: block;
				margin-left: 12rpx;
			}
		}
	}

	textarea,
	input {
		flex: 1;
		font-size: $font-size-base;
		margin-left: 20rpx;
		padding: 0;
	}

	textarea {
		margin-top: 6rpx;
		height: 100rpx;
		padding-bottom: 20rpx;
		padding-top: 20rpx;
		line-height: 50rpx;
	}
}

.edit-wrap > .edit-item + .edit-item {
	border-top: 2rpx solid #ebedf0;
}

.add {
	margin-top: 60rpx;
	height: 80rpx;
	line-height: 80rpx !important;
	border-radius: 80rpx;
	font-weight: 500;
	width: calc(100% - 60rpx);
	margin-left: 30rpx;
}

.btn {
	position: fixed;
	width: 100%;
	bottom: 30rpx;
	height: auto;
	padding-bottom: constant(safe-area-inset-bottom);
	/*兼容 IOS<11.2*/
	padding-bottom: env(safe-area-inset-bottom);
	/*兼容 IOS>11.2*/
}

.country-popup {
		width: 100%;
		background: #F8F7FC;
		
		// height: auto;
		overflow: auto;
		.shops-header-box {
			width: 100%;
			// height: 88rpx;
			background: #fff;
			padding: 0px 32rpx;
			box-sizing: border-box;
			margin-bottom: 8rpx;
			.shops-header {
				width: 100%;
				height: 88rpx;
				display: flex;
				align-items: center;
				justify-content: space-between;
				.shops-left {
					display: flex;
					align-items: center;
					.shops-header-title {
						font-size: 36rpx;
						font-family: PingFangSC-Semibold, PingFang SC;
						font-weight: 600;
						color: #292929;
						line-height: 50rpx;
						margin-left: 6rpx;
					}
				}
				.shops-right {
					display: flex;
					align-items: center;
					.home-icon {
						width: 32rpx;
						height: 32rpx;
						margin-right: 12rpx;
					}
					.to-home {
						font-size: 26rpx;
						color: #31bb6d;
					}
				}
			}
				
			.search-wrap {
				flex: 0.5;
				padding: 30rpx 30rpx;
				font-size: $font-size-tag;
				display: flex;
				align-items: center;
				.input-wrap {
					flex: 1;
					display: flex;
					justify-content: space-between;
					align-items: center;
					background: $color-bg;
					height: 70rpx;
					padding-left: 10rpx;
					border-radius: 70rpx;
					input {
						width: 90%;
						background: $color-bg;
						font-size: $font-size-tag;
						height: 50rpx;
						padding: 10rpx 25rpx 10rpx 40rpx;
						line-height: 50rpx;
						border-radius: 40rpx;
					}
					text {
						font-size: $font-size-toolbar;
						color: $color-tip;
						width: 80rpx;
						text-align: center;
						margin-right: 20rpx;
					}
				}
				
			}
				
		}
		.country-ul {
			height: 100vh;
			// padding-top: 100rpx;
			overflow: auto;
			.country-li {
				width: 100%;
				background: #fff;
				padding: 0px 32rpx;
				box-sizing: border-box;
				.li-name {
					width: 100%;
					height: 110rpx;
					display: flex;
					align-items: center;
					justify-content: space-between;
					border-bottom: 2rpx solid #E8EDF5;
					text {
						font-size: 32rpx;
						color: #353535;
						.h6 {
							margin-left: 15rpx;
							color: #92969E;
						}
					}
					.sel-icon {
						width: 36rpx;
						height: 36rpx;
					}
				}
			}
		}
	}



</style>
